import sys

import uymas.zy.cliutil
import uymas.zy.uymas as uy
import os
import img2pdf
from PIL import Image

# 2024年7月17日
# 图片转pdf
"""

# 图片压缩
get-ChildItem *.jpg | foreach {ffmpeg -i $_.FullName -fs 100KB "./mini/$($_.Name)"  -y}

# '-qscale:v' 越大图片越小([1-12])
get-ChildItem *.jpg | foreach {ffmpeg -i $_.FullName -vcodec mjpeg '-qscale:v' 12 -preset ultrafast "./mini/$($_.Name)"  -y}
"""


def reader_dir(v_dir: str, output_name="output.pdf"):
    """
    读取目录文件并将其保存为pdf
    :param v_dir:
    :param output_name:
    :return:
    """
    image_list = []
    for root, dirs, files in os.walk(v_dir):
        for file in files:
            # print(f'{root}/{file}')
            image_list.append(f"{root}/{file}")

    # 将所有图片转换为RGB模式（PDF需要）
    pdf_bytes = img2pdf.convert([Image.open(i).filename for i in image_list])

    # 将转换后的字节写入PDF文件
    with open(output_name, "wb") as file:
        file.write(pdf_bytes)
        print("文件写入成功")


def reader_dir_2(v_dir: str):
    image_list = []
    for root, dirs, files in os.walk(v_dir):
        for file in files:
            # print(f'{root}/{file}')
            image_list.append(f"{root}/{file}")

    # 将所有图片转换为RGB模式（PDF需要）
    img_bytes = [Image.open(i).filename for i in image_list]
    # 将每张图片转换为PDF页面，使用自定义页面尺寸
    pdf_bytes = []
    for img in img_bytes:
        page_pdf = img2pdf.add(img, pagesize=(img.width, img.height))
        pdf_bytes.append(page_pdf)

    # 将转换后的字节写入PDF文件
    with open("output.pdf", "wb") as file:
        file.write(pdf_bytes)
        print("文件写入成功")


def action_command(opt: uy.Option):
    """
    图片转pdf
    :return:
    """
    v_path = opt.action
    if not v_path:
        v_path = uymas.zy.cliutil.require_input("请输图片所在目录（exit/q 退出）：")

    if v_path == "exit" or v_path == "q":
        sys.exit()

    time_spend_fn = uymas.get_time_spend()
    output_name = "output.pdf"
    output_name = opt.get_raw("output", "o", def_str=output_name)

    print(f"准备将 {v_path} 图片转为pdf文件……")
    print(f"文件保存为 {output_name}")
    reader_dir(v_path, output_name)

    print()
    print("用时 {}s".format(time_spend_fn()))
